package com.blacktry.controller.blog;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blacktry.entity.blog.ArticleLabel;
import com.blacktry.entity.blog.ArticleSort;
import com.blacktry.entity.blog.Articles;
import com.blacktry.entity.blog.Labels;
import com.blacktry.entity.enums.OprLogConst;
import com.blacktry.entity.model.ApiResult;
import com.blacktry.entity.model.Vo.BlogVo;
import com.blacktry.entity.model.request.ArticleLabelRequest;
import com.blacktry.entity.model.request.ArticlesRequest;
import com.blacktry.entity.model.vueVO.ArticleVo;
import com.blacktry.service.ArticleLabelService;
import com.blacktry.service.ArticleSortService;
import com.blacktry.service.ArticlesService;
import com.blacktry.service.LabelsService;
import com.blacktry.utils.ApiResultHandler;
import com.blacktry.utils.RedisUtil;
import com.blacktry.utils.blog.BlogView;
import com.blacktry.utils.log.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author blackTry
 * @since 2022-02-07
 */
@Api(value="文章模块", tags = "文章管理接口")
@RestController
@RequestMapping("/articles")
public class ArticlesController {

    @Autowired
    private ArticlesService articlesService;

    @OperLog(operModul = "文章管理-分页查看所有文章",operType = OprLogConst.SELECT,operDesc = "分页查看所有文章功能")
    @ApiOperation("分页查看所有用文章")
    @PostMapping("/findAll")
    public ApiResult<Page<Articles>> findAll(){
        return ApiResultHandler.buildApiResult(200, "请求成功！", articlesService.list());
    }

    @OperLog(operModul = "文章管理-获取ES抓取的文章列表",operType = OprLogConst.SELECT,operDesc = "获取ES抓取的文章列表")
    @ApiOperation("获取ES抓取的文章列表")
    @PostMapping("/findAllForES")
    public List<BlogVo> findAllForES(){
        return articlesService.findAllForES();
    }



    @Autowired
    LabelsService labelsService;
    @Autowired
    ArticleSortService articleSortService;

    @Autowired
    ArticleLabelService articleLabelService;
    //添加博客文章
    @OperLog(operModul = "添加博客文章",operType = OprLogConst.SELECT,operDesc = "添加博客文章")
    @ApiOperation("添加博客文章")
    @PostMapping("/insert/{labelName}/{sortId}")
    public ApiResult insertArticle(@RequestBody Articles articles,@PathVariable("labelName") String labelName,@PathVariable("sortId") String sortId, Principal principal){
        String username= principal.getName();
        articles.setUserId(username);
        String[] a=labelName.split(",");
        //得到分类id
        String[] b=sortId.split(",");

        articlesService.save(articles);
        Integer id=articles.getArticleId();
//        把标签填充到lables表中 并填充articleLable表
        for (int i = 0; i <a.length ; i++) {
            Labels labels=new Labels();
            labels.setLabelName(a[i]);
          labelsService.save(labels);
          Integer id2=labels.getLabelId();
            ArticleLabel articleLabel=new ArticleLabel();
           articleLabel.setArticleId(id);
            articleLabel.setLabelId(id2);
            articleLabelService.save(articleLabel);
        }
//        向articlesSort表中插入数据
        for (int i = 0; i <b.length ; i++) {
            ArticleSort articleSort=new ArticleSort();
            articleSort.setArticleId(id);
            Integer aa=Integer.parseInt(b[i]);
            articleSort.setSortId(aa);
            articleSortService.save(articleSort);
        }
        return  ApiResultHandler.buildApiResult(200, "请求成功！");
    }


    @OperLog(operModul = "查询热点文章",operType = OprLogConst.SELECT,operDesc = "查询热点文章")
    @ApiOperation("查询热点文章")
    @GetMapping("/selectHotArticle")
    public ApiResult<ArticleVo[]> selectHotArticle(){
        return ApiResultHandler.buildApiResult(200, "请求成功！",articlesService.selectHotArticle());
    }


    @OperLog(operModul = "根据姓名查询所发布的文章",operType = OprLogConst.SELECT,operDesc = "根据姓名查询所发布的文章")
    @ApiOperation("根据姓名查询所发布的文章")
    @GetMapping("/selectArticleByUserName/{userId}")
    public ApiResult<ArticleVo[]> selectArticleByUserName(@PathVariable("userId") String userId){
        return ApiResultHandler.buildApiResult(200, "请求成功！",articlesService.selectArticleByUserName(userId));
    }

    @Autowired
    private RedisUtil redisUtil;

    @BlogView // 注解统计浏览量
    @OperLog(operModul = "文章管理-查看单个文章",operType = OprLogConst.SELECT,operDesc = "查看单个文章")
    @ApiOperation("查看单个文章")
    @GetMapping("/selectOneArticle/{id}")
    public ApiResult<Articles> selectOneArticle(@PathVariable("id") String id){
        Articles articles = articlesService.getById(id);
        final String QUESTION_KEY = "BLOG_ID:";
        Long viewCount = redisUtil.size(QUESTION_KEY + id);
        articles.setArticleViews(viewCount.intValue() + articles.getArticleViews());
        return ApiResultHandler.buildApiResult(200, "请求成功！",articles);
    }

    @OperLog(operModul = "文章管理-分页条件文章", operType = OprLogConst.SELECT, operDesc = "分页条件文章")
    @ApiOperation("分页条件文章")
    @PostMapping("/selectArticles/{page}/{size}")
    public ApiResult<Page<ArticleLabelRequest>> selectArticles(@RequestBody ArticlesRequest articlesRequest, @DefaultValue("1") @PathVariable("page") Integer page, @DefaultValue("6") @PathVariable("size") Integer size) {
        Page<Articles> articlesPage = new Page<>(page, size);
        return ApiResultHandler.buildApiResult(200, "请求成功！", articlesService.selectArticles(articlesRequest, articlesPage));
    }


    //根据articleId更新博客文章
    @OperLog(operModul = "更新博客文章",operType = OprLogConst.SELECT,operDesc = "更新博客文章")
    @ApiOperation("更新博客文章")
    @PostMapping("/updateArticle/{articleId}{labelName}/{sortId}")
    public ApiResult updateArticle(@RequestBody Articles articles,@PathVariable("articleId") Integer articleId,@PathVariable("labelName") String labelName,@PathVariable("sortId") String sortId, Principal principal){

        //更新文章
        articlesService.updateArticleByArticleId(articles);

        //查询出旧文章的sortId
        Integer[] li=articleSortService.selectSortId(articleId);
        //得到新的分类id
        String[] b=sortId.split(",");
        Integer[] ll={};
        for (int i = 0; i <b.length ; i++) {
            ll[i]=Integer.parseInt(b[i]);
        }
        Arrays.sort(li);
        Arrays.sort(ll);
        //分类前后一致
        if(Arrays.equals(li, ll)){
            //不做处理
        }else {
            //分类前后不一致
            //删除旧文章的articleSort
            articleSortService.deleteArticleSort(articleId);
            //添加新的
            for (int i = 0; i <ll.length ; i++) {
                ArticleSort articleSort=new ArticleSort();
                articleSort.setArticleId(articleId);
                Integer aa=Integer.parseInt(b[i]);
                articleSort.setSortId(aa);
                articleSortService.save(articleSort);
            }
        }
        // 查询出旧文章的 labelId
       Integer[] n=articleLabelService.selectLabelIdByArticleId(articleId);
        //查出旧文章的标签名字
        String[] mm={};
        for (int i = 0; i < n.length; i++) {
            String x=articleLabelService.selectLableNameById(n[i]);
            mm[i]=x;
        }
       //新标签名
        String[] a=labelName.split(",");
        Arrays.sort(a);
        Arrays.sort(mm);
        if(Arrays.equals(a, mm)){
            //新标签和旧标签一样  不做处理
        }else{
            //删除旧文章的articleLabel
            articleLabelService.deleteArticleLabel(articleId);
            //删除旧文章的label
            for (int i = 0; i <n.length ; i++) {
                labelsService.deleteLableById(n[i]);
            }
            //        把标签填充到lables表中 并填充articleLable表
            for (int i = 0; i <a.length ; i++) {
                Labels labels=new Labels();
                labels.setLabelName(a[i]);
                labelsService.save(labels);

                Integer id2=labels.getLabelId();
                ArticleLabel articleLabel=new ArticleLabel();
                articleLabel.setArticleId(articleId);
                articleLabel.setLabelId(id2);
                articleLabelService.save(articleLabel);
            }
        }
        return  ApiResultHandler.buildApiResult(200, "请求成功！");
    }
}






















//        //删除旧文章的articleSort
//        articleSortService.deleteArticleSort(articleId);
//        //删除旧文章的articleLabel
//        articleLabelService.deleteArticleLabel(articleId);
//        //查询出旧文章的 labelId
//        List<ArticleLabel> list=articleLabelService.selectArticleLabelByArticleId(articleId);
//        //删除旧文章的label
//        for (int i = 0; i <list.size() ; i++) {
//            labelsService.deleteLableById(list.get(i).getLabelId());
//        }
//
//        String username= principal.getName();
//        articles.setUserId(username);
//        String[] a=labelName.split(",");
//        //得到分类id
//        String[] b=sortId.split(",");
//        articlesService.save(articles);
//        Integer id=articles.getArticleId();
////        把标签填充到lables表中 并填充articleLable表
//        for (int i = 0; i <a.length ; i++) {
//            Labels labels=new Labels();
//            labels.setLabelName(a[i]);
//            labelsService.save(labels);
//            Integer id2=labels.getLabelId();
//            ArticleLabel articleLabel=new ArticleLabel();
//            articleLabel.setArticleId(id);
//            articleLabel.setLabelId(id2);
//            articleLabelService.save(articleLabel);
//        }
////        向articlesSort表中插入数据
//        for (int i = 0; i <b.length ; i++) {
//            ArticleSort articleSort=new ArticleSort();
//            articleSort.setArticleId(id);
//            Integer aa=Integer.parseInt(b[i]);
//            articleSort.setSortId(aa);
//            articleSortService.save(articleSort);
//        }


